import shutil
import time
import uiautomator2 as u2
import os
import sys
import datetime

# 设备id  237db2dd    ca6b0c97    a253684     a7db9a76    91022c36
devicesid = "91022c36"
# 连接设备
device = u2.connect(devicesid)

# 相机名称
appname = "com.android.camera"


# 录像模块
def video(timel, num, fullstatus="off"):
    if device(text="录像").wait(timeout=2):
        device(text="录像").click()
    time.sleep(2)
    description("超高清 4K, 30fps", timel, num, fullstatus=fullstatus)
    description("全高清 1080p, 30fps", timel, num, fullstatus=fullstatus)
    description("全高清 1080p, 60fps", timel, num, fullstatus=fullstatus)
    description("高清 720p, 30fps", timel, num, fullstatus=fullstatus)


# 模式切换  desc为模式description  timel为时间
""""test
    description("超高清 4K, 30fps", 2, "on")
    description("全高清 1080p, 30fps", 2, "off")
    description("全高清 1080p, 60fps", 2, "on")
    description("高清 720p, 30fps", 2, "off")
"""


# 专业模式切换lens
def perfess_switch(lens, mod="拍照"):
    # open专业
    if device(resourceId="com.android.camera:id/mode_select_item", text="专业").exists:
        device(resourceId="com.android.camera:id/mode_select_item", text="专业").click()
        time.sleep(2)
        # 切换录像
        if mod == "录像" and device(resourceId="com.android.camera:id/v9_capture_picker_layout_horizontal").wait(
                timeout=5):
            device(resourceId="com.android.camera:id/v9_capture_picker_layout_horizontal").click()
            time.sleep(1)
        if device(resourceId="com.android.camera:id/manually_item_key", text="LENS").wait(timeout=5):
            device(resourceId="com.android.camera:id/manually_item_key", text="LENS").click()
            if lens == "WIDE" and device(resourceId="com.android.camera:id/extra_item_text", text="WIDE").exists:
                device(resourceId="com.android.camera:id/extra_item_text", text="WIDE").click()
            if lens == "UW" and device(resourceId="com.android.camera:id/extra_item_text", text="UW").exists:
                device(resourceId="com.android.camera:id/extra_item_text", text="UW").click()
            if lens == "MACRO" and device(resourceId="com.android.camera:id/extra_item_text", text="MACRO").exists:
                device(resourceId="com.android.camera:id/extra_item_text", text="MACRO").click()


# video switch
def description(desc, timel, num, zoom=0, modelname="录像", shrotvideo="off", fullstatus="off", desc_shake="超级防抖，开启状态",
                switch="rear", beauty="off"):
    timel = timelformat(timel)
    # 切换模式
    if modelname == "萌拍":
        switchmodel(modelname)
        time.sleep(1)
    # 拍照与录像切换
    if shrotvideo == "on" and device(resourceId="com.android.camera:id/v9_capture_picker_layout_horizontal").exists:
        device(resourceId="com.android.camera:id/v9_capture_picker_layout_horizontal").click()
        time.sleep(2)
    # 前置或者后置摄像头
    if switch == "front" and modelname != "萌拍" and device(
            resourceId="com.android.camera:id/v9_capture_picker_layout_horizontal").exists:
        device(resourceId="com.android.camera:id/v9_capture_picker_layout_horizontal").click()
        time.sleep(1)
    elif switch == "front" and device(resourceId="com.android.camera:id/popup_right_tip_image").exists:
        device(resourceId="com.android.camera:id/popup_right_tip_image").click()
        time.sleep(1)
    # 是否开启美颜
    if beauty == "on" and device(description="打开美化功能面板").wait():
        device(description="打开美化功能面板").click()
        if device(resourceId="com.android.camera:id/beauty_level_adjust_seekbar").wait():
            device(resourceId="com.android.camera:id/beauty_level_adjust_seekbar").click()
            device.press("back")
            time.sleep(1)
    # 是否切换ZOOM
    if zoom > 0:
        switchlens(zoom)
    time.sleep(2)
    if device(text=modelname).wait(timeout=2):
        if device(resourceId="com.android.camera:id/top_config_12").wait(timeout=2):
            device(resourceId="com.android.camera:id/top_config_12").click()
            time.sleep(1)
            if fullstatus == "on" and device(resourceId="com.android.camera:id/extra_tootle_item_layout",
                                             description="电影模式,关闭状态").exists:
                device(resourceId="com.android.camera:id/extra_tootle_item_layout", description="电影模式,关闭状态").click()
            elif fullstatus == "off" and device(resourceId="com.android.camera:id/extra_tootle_item_layout",
                                                description="电影模式,开启状态").exists:
                device(resourceId="com.android.camera:id/extra_tootle_item_layout", description="电影模式,开启状态").click()
            else:
                pass
            time.sleep(2)
            # 切换resolution
            if device(description=desc + ", 已选中").exists:
                device(description=desc + ", 已选中").click()
            if device(description=desc).exists:
                device(description=desc).click()
            if desc_shake == "超级防抖，关闭状态":
                time.sleep(1)
                device.press("back")
                time.sleep(2)
            # 超级防抖，是否开启
            if desc_shake == "超级防抖，关闭状态" and device(description=desc_shake).wait(timeout=2):
                device(description=desc_shake).click()
                time.sleep(2)
            for i in range(0, num, 1):
                time.sleep(2)
                device.shell("input keyevent KEYCODE_CAMERA")
                if modelname != "短视频" and modelname != "萌拍" and timel != "00:15" and device(text=timel).wait(timeout=310):
                    device.shell("input keyevent KEYCODE_CAMERA")
                if modelname == "短视频":
                    device(description="完成拍摄").click()
                    time.sleep(12)
                if modelname == "萌拍" and device(description="完成拍摄").wait(timeout=17):
                    device(description="完成拍摄").click()
            # 超级防抖,关闭
            if device(description="超级防抖，开启状态").exists:
                device(description="超级防抖，开启状态").click()
                time.sleep(2)
            # 萌拍关闭
            if device(description="萌拍,双击退出").exists:
                device(description="萌拍,双击退出").click()
                time.sleep(1)
    print(str(datetime.datetime.now()) + " : " + "[" + devicesid + "] " + "<--录制视频(完成)" + desc + ",时长为：" + timel)


# camera num
def numcase(timel, num):
    timel = timelformat(timel)
    for i in range(0, num, 1):
        time.sleep(2)
        device.shell("input keyevent KEYCODE_CAMERA")
        if device(text=timel).wait(timeout=310):
            device.shell("input keyevent KEYCODE_CAMERA")


# eis模块
def videoEis():
    print(str(datetime.datetime.now()) + " : " + "[" + devicesid + "] " + "EIS 防抖开关")
    if device(text="录像").wait(timeout=5):
        device(text="录像").click()
        time.sleep(2)
        if device(resourceId="com.android.camera:id/top_config_12").wait(timeout=2):
            device(resourceId="com.android.camera:id/top_config_12").click()
            if device(text="设置").wait():
                device(resourceId="com.android.camera:id/extra_tootle_item_layout", description="设置").click()
            if device(text="视频防抖").wait():
                device.xpath(
                    '//*[@resource-id="com.android.camera:id/recycler_view"]/android.widget.LinearLayout[2]/android.widget.LinearLayout[1]').click()
                device.press("back")


# 导出文件 arg1:导出路径
def inputFile(path):
    os.system("adb -s" + devicesid + " pull")
    print("")


# 清除文件 arg1：清除路径
def clearFile(path):
    os.system("adb -s " + devicesid + " shell rm -rf ")
    print()


# 清除相机全部数据
def clearCamera():
    print(str(datetime.datetime.now()) + " : " + "[" + devicesid + "] " + "-->清除APP[" + appname + "]的数据")
    os.system("adb shell pm clear com.android.camera")
    # os.system("fullstatus="off" shell am force-stop  com.android.camera")
    os.system("adb shell am start com.android.camera")
    device(resourceId="android:id/button1").click()
    device(resourceId="com.lbe.security.miui:id/permission_allow_foreground_only_button").click()


# 还原相机默认设置
def redefualtCamera():
    if device(resourceId="com.android.camera:id/top_config_12").wait():
        device(resourceId="com.android.camera:id/top_config_12").click()
    if device(text="设置").wait():
        device(resourceId="com.android.camera:id/extra_tootle_item_layout", description="设置").click()
    if device(text="相机设置").wait():
        device.swipe(200, 1800, 200, 700, 0.1)
    device(resourceId="android:id/title", text="还原默认设置").click()
    device(resourceId="android:id/button1").click()
    if device(resourceId="android:id/button1").wait_gone():
        device.press("back")
    if device(resourceId="com.android.camera:id/parentPanel").wait(timeout=1):
        device(resourceId="android:id/button1").click()
    elif device(text="同意").wait():
        device(resourceId="android:id/button1").click()


# 下载其他模块短视频萌拍
def downloadmod(modname):
    print(str(datetime.datetime.now()) + " : " + "[" + devicesid + "] " + "-->下载模块" + modname)
    device(resourceId="com.android.camera:id/mode_select_item", text="更多").click()
    time.sleep(1)
    if modname == "短视频":
        device(resourceId="com.android.camera:id/mode_name", text="短视频").click()
    if modname == "萌拍":
        device(resourceId="com.android.camera:id/mode_name", text="萌拍").click()
        time.sleep(285)
    time.sleep(100)
    print(str(datetime.datetime.now()) + " : " + "[" + devicesid + "] " + "-->下载模块" + modname + "完成")


# 开机解锁
def openscreen_on():
    result = device.shell("dumpsys window |grep screenState").output.split('=')[1]
    if result == "SCREEN_STATE_OFF\n":
        device.screen_on()
        device.swipe(200, 1800, 200, 700, 0.1)


# 慢动作模块
def slowmotion(timel, num):
    device.app_start(appname)
    redefualtCamera()
    time.sleep(2)
    videoEis()
    if device(text="拍照").wait():
        device(resourceId="com.android.camera:id/mode_select_item", text="拍照").click()
    time.sleep(2)
    if device(text="更多").wait(timeout=2):
        device(resourceId="com.android.camera:id/mode_select_item", text="更多").click()
    time.sleep(2)
    if device(text="慢动作").wait(timeout=2):
        device.xpath(
            '//*[@resource-id="com.android.camera:id/modes_content"]/android.widget.FrameLayout[7]/android.widget.FrameLayout[1]').click()
        time.sleep(1)
        slowmotionSwitch("高清 720p", "960FPS", timel, num)
        slowmotionSwitch("高清 720p", "240FPS", timel, num)
        slowmotionSwitch("高清 720p", "120FPS", timel, num)
        slowmotionSwitch("全高清 1080p", "120FPS", timel, num)


# 慢动作镜头切换
def slowmotionSwitch(desc1, desc2, timel, num):
    timel = timelformat(timel);
    if device(resourceId="com.android.camera:id/top_config_12").wait(timeout=2):
        device(resourceId="com.android.camera:id/top_config_12").click()
    if device(description=desc1).wait(timeout=1):
        device(description=desc1).click()
    if device(description=desc2).wait(timeout=2):
        device(description=desc2).click()
    print(str(datetime.datetime.now()) + " : " + "[" + devicesid + "] " + "-->录制慢动作" + desc1 + desc2 + ",时长为：" + timel)
    for i in range(0, num, 1):
        time.sleep(1)
        device.shell("input keyevent KEYCODE_CAMERA")
        if desc2 == "960FPS":
            time.sleep(10)
        else:
            if device(text=timel).wait(timeout=320):
                device.shell("input keyevent KEYCODE_CAMERA")


# 切换前后置


def test(timel):
    print("  ")


# 3.前置视频模式
def frontVideo():
    # 切换前置
    if device(resourceId="com.android.camera:id/v9_capture_picker_layout_horizontal").wait():
        device(resourceId="com.android.camera:id/v9_capture_picker_layout_horizontal").click()
    print(" ")


# 秒格式化%M:%S
def timelformat(timel):
    if timel < 10:
        timel = "00:0" + str(timel);
    elif timel > 60:
        if int(timel / 60) >= 10:
            if timel % 10 > 0:
                if timel % 60 >= 10:
                    timel = str(int(timel / 60)) + ":" + str((timel % 60))
                else:
                    timel = str(int(timel / 60)) + ":" + "0" + str((timel % 10))
            else:
                timel = str(int(timel / 60)) + ":" + str((timel % 60))
        else:
            if timel % 10 >= 0:
                if timel % 60 >= 10:
                    timel = "0" + str(int(timel / 60)) + ":" + str((timel % 60))
                else:
                    timel = "0" + str(int(timel / 60)) + ":" + "0" + str((timel % 10))
            else:
                timel = "0" + str(int(timel / 60)) + ":" + str((timel % 60))
    else:
        timel = "00:" + str(timel);
    return timel


def str2sec(x):
    '''
    字符串时分秒转换成秒
    '''
    h, m, s = x.strip().split(':')  # .split()函数将其通过':'分隔开，.strip()函数用来除去空格
    timeArray = time.strptime(str(datetime.timedelta(seconds=2666)), "%H:%M:%S")
    otherStyleTime = time.strftime("%M:%S", timeArray)
    return int(h) * 3600 + int(m) * 60 + int(s)  # int()函数转换成整数运算


# adb导出视频函数 path1手机目录  path2电脑文件目录
def pullfile(path1, path2):
    if os.path.exists(path2):
        os.mkdir(path2)
    elif not os.path.exists(path2):
        os.remove(path2)
    else:
        print("目录存在错误")
    print(str(datetime.datetime.now()) + " : " + "[" + devicesid + "] " + "-->导出文件：\n" + path1 + " to " + path2)
    os.system("adb -s " + devicesid + " pull " + path1 + " " + path2)


#
def adbpull(resultpath):
    filepath = os.path.abspath(os.path.join(os.getcwd(), "..")) + "\\bat"
    os.system("cd " + filepath + " &&" + "start /min  call adb-pull.bat " + devicesid + " " + resultpath)
    time.sleep(200)


# 切换更多模式
def switchmodel(text):
    if device(resourceId="com.android.camera:id/mode_select_item", text="更多").exists:
        device(resourceId="com.android.camera:id/mode_select_item", text="更多").click()
    else:
        device(resourceId="com.android.camera:id/mode_select_item", text="拍照").click()
        time.sleep(2)
        if device(resourceId="com.android.camera:id/mode_select_item", text="更多").exists:
            device(resourceId="com.android.camera:id/mode_select_item", text="更多").click()
    time.sleep(1)
    if device(resourceId="com.android.camera:id/mode_name", text=text).wait(timeout=5):
        device(resourceId="com.android.camera:id/mode_name", text=text).click()
        time.sleep(2)
    else:
        device.swipe(700, 1400, 700, 1000, 0.1)
        if device(resourceId="com.android.camera:id/mode_name", text=text).wait(timeout=5):
            device(resourceId="com.android.camera:id/mode_name", text=text).click()
            time.sleep(2)


# 切换变焦ZOOM 0.6倍变焦 1.0倍变焦 2.0倍变焦
def switchlens(desc):
    if desc == 0.6 and device(description="0.6倍变焦").exists:
        device(description="0.6倍变焦").click()
    elif desc == 1.0 and device(description="1.0倍变焦").exists:
        device(description="1.0倍变焦").click()
    elif desc == 2.0 and device(description="2.0倍变焦").exists:
        device(description="2.0倍变焦").click()
    else:
        print("切换ZOOM失败: " + desc)


# stream
def streamlog():
    r = device.shell("logcat | grep \"camhal output fps\"", stream=True)
    # r: requests.models.Response
    deadline = time.time() + 10  # run maxium 10s
    try:
        for line in r.iter_lines():  # r.iter_lines(chunk_size=512, decode_unicode=None, delimiter=None)
            if time.time() > deadline:
                break
            print("Read:", line.decode('utf-8'))
    finally:
        r.close()  # this method must be called

#安装apk

#启动apk

#退出apk

#开启wifi/数据,GPS,NFC,蓝牙


if __name__ == '__main__':
    switchmodel("萌拍")

''' 
    if device(text="00:30").wait(timeout=40):
        print("3o")
    
'''
